package com.example.smartagrisys.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具类
 */
public class MD5Util {

    /**
     * MD5加密
     * @param str 需要加密的字符串
     * @return 加密后的字符串
     */
    public static String encrypt(String str) {
        if (str == null || str.isEmpty()) {
            return null;
        }
        
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] byteDigest = md.digest();
            
            StringBuilder sb = new StringBuilder();
            for (byte b : byteDigest) {
                sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
            }
            
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 验证密码
     * @param password 明文密码
     * @param md5Password MD5加密后的密码
     * @return 是否匹配
     */
    public static boolean verify(String password, String md5Password) {
        return md5Password.equals(encrypt(password));
    }
} 